package com.cilico.single.components;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.cilico.single.ConfigManager;
import com.cilico.single.Mid;
import com.cilico.single.shopcart.ShopCart;
import com.cilico.single.utils.Constant;
import com.cilico.single.utils.Utils;
import com.cilico.single.view.BaseView;
import com.cilico.single.view.Channel;
import com.cilico.single.view.FormLayout;

/**
 * 状�?栏单个icon
 * @author lv.xiangan
 *
 */
public class TabItem extends TextView implements Component {
	boolean focus_ = false;
	int textColor_; // normal text color.
	private int focusTextColor_; // focus text color.
	int x_;
	int w_;
	int h_;
	int totalTabW_;
	int width_;
	int height_;
	int xDown_;
	int xTabDown_;
	public static int currentTab_;
	// 该变量只配合currentTab_使用，存的是点击该控件后的一个临时存储变�?
	public static int saveCurrentTab_;
	
	private int bgColor_; // background color.
	// tab单元个数
	// tabbar文字单元总长
	int tabSize_;
	int totalWidth_;
	// 箭头图片的覆盖长�?
	int lengthBitmap_;
	String label_;
	// 背景图片
	static Bitmap imgBackground_;
	Paint font_;

	String[] arrText_;
	Bitmap[] arrBitmap_;
	// 状�?栏高亮显示的状�?集合
	Bitmap[] arrBitmapD_;
	final int TAB_TEXT_MARGIN_X = 5; // The horizonal margin of tab
	// 两边箭头图片与文字的间距
	final int TAB_BITMAP_MARGIN = 5;
	// words.
	final int TAB_TEXT_ABOVE_MARGIN = 2; // The vertical margin above
	// tab words.
	final int TAB_TEXT_BELOW_MARGIN = 2; // The vertical margin below
	// tab words.
	final int TAB_BOTTOM_MARGIN = 1; // The vertical margin below the
	ComponentListener listener_;
	boolean isImgUnit_;
	// arrow images.
	private Bitmap arrowIconLeftOn_;
	private Bitmap arrowIconLeftOff_;
	private Bitmap arrowIconRightOn_;
	private Bitmap arrowIconRightOff_;
	private int arrowWidth_;
	BaseView bv_;

	// imgOn and imgOff must be the same size.
	TabItem(Context context, String[] texts, Bitmap[] bgs, Bitmap[] bgsD, Bitmap on, Bitmap off, Bitmap background, Bitmap arr) {
		super(context);
		bv_ = (BaseView) context;
		this.setFocusable(true);
		this.setFocusableInTouchMode(true);
		arrText_ = texts;
		arrBitmap_ = bgs;
		arrBitmapD_ = bgsD;
		createArrow(arr);
		textColor_ = 0xFF699DE0;
		focusTextColor_ = Color.WHITE;
		font_ = new Paint();
		font_.setTypeface(Typeface.DEFAULT_BOLD);
		font_.setTextSize(Utils.getScaledValue(ConfigManager.SIZE_TABBAR));
		width_ = Utils.screenWidth_;
		if (null != arrText_)
			tabSize_ = this.arrText_.length;
		if (null == imgBackground_ && null != background)
			imgBackground_ = Utils.makeButton(background, width_);
	}

	private void createArrow(Bitmap arr) {
		try {
			if (null == arr)
				return;
			int w = arr.getWidth() / 2;
			arrowWidth_ = w;
			int h = arr.getHeight();
			if (BaseView.arrowIcons_ == null)
				BaseView.arrowIcons_ = BaseView.mid_.constant_.getArrowIcon(arr, w, h);
			arrowIconLeftOn_ = BaseView.arrowIcons_[0];
			arrowIconLeftOff_ = BaseView.arrowIcons_[1];
			arrowIconRightOn_ = BaseView.arrowIcons_[2];
			arrowIconRightOff_ = BaseView.arrowIcons_[3];
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Utils.printException(e);
		}
	}

	protected void reculculateMaxUnitNum() {

		for (int i = 0; i < tabSize_; i++)
			totalWidth_ += Math.max((int) (font_.measureText(arrText_[i]) + (TAB_TEXT_MARGIN_X << 1)),
					arrBitmap_[i].getWidth());

	}

	/** 
	 * 设置该tab获得焦点且已选将该组中的其他控件全部设置为不获得焦点且为+不�?中状态�?
	 * @param isPressed
	 */
	public void setSelectedStatute(boolean isPressed) {
		if (!isPressed) // 没有按下
			this.setSelected(true);
		else
			this.requestFocus();
	}

	public boolean onTouchEvent(MotionEvent me) {
		int x = (int) me.getX();
		// 取得触摸动作类型
		int action = me.getAction();
		switch (action) {
		// 按下操作
		case MotionEvent.ACTION_DOWN:
			xDown_ = (int) me.getX();
			xTabDown_ = (int) me.getX();
			this.requestFocus();
			int tabWidth = 0;
			int length = 0;
			// 单个箭头宽度
			int arrWidth = arrowWidth_;
			// 用户的点击长�?
			int pointLength = x - x_ - arrWidth;
			for (int i = 0; i < tabSize_; i++) {
				tabWidth = Math.max((int) (font_.measureText(arrText_[i]) + (TAB_TEXT_MARGIN_X << 1)),
						arrBitmap_[i].getWidth());
				if ((length <= pointLength) && (length + tabWidth) >= pointLength) {
					if (length + x_ < 0) {
						// 校正标签界面左端显示
						x_ = -length;
					} else if ((length + tabWidth) > (-x_ - lengthBitmap_ + width_)) {
						// 校正标签右端显示
						x_ = width_ - length - tabWidth - (lengthBitmap_ << 1);
					}
					currentTab_ = i;
					this.invalidate();
					break;
				}
				length += tabWidth;
			}
			break;
		case MotionEvent.ACTION_MOVE:
			int temp = x - xDown_;
			int xLimitingvalue = width_ - (lengthBitmap_ << 1) - totalWidth_;
			// 如果偏移未�??���???�极限，则累加偏移�?
			if (((x_ + temp) > xLimitingvalue) && ((x_ + temp) < 0))
				x_ = x_ + temp;
			xDown_ = x;
			this.invalidate();
			break;
		case MotionEvent.ACTION_UP:
			if (currentTab_ >= arrText_.length){
				break;
			}
			// BaseView.CHANGEWORKED = false;
			int xUp = (int) me.getX();
			// 移动位移8个像素以上算拖动,不响应弹起方�?
			if (Math.abs(xUp - xTabDown_) > 8) {
				return super.onTouchEvent(me);
			}
			ShopCart.clearData();
			if (BaseView.mid_.poiRepo_.getActionSize() >= 0) {
				ViewGroup vg = (ViewGroup) this.getParent();
				if (vg instanceof StatusBar) {
					changeSelectTab();
				} else {
					changeTab();
				}
				BaseView.ttimerIscannel_ = true;
				if (Table.tableTimer_ != null) {
					Table.tableTimer_.cancel();
					Table.tableTimer_ = null;
				}
			}
			
			break;
		default:
			return super.onTouchEvent(me);
		}
		return true;
	}

	private void changeSelectTab() {
		BaseView bv = (BaseView) this.getContext();
		if ((currentTab_ == 0 && StatusBar.ARRVALUE[StatusBar.ARRVALUE.length-1].indexOf("help") != -1) || ( currentTab_ < arrText_.length && arrText_[currentTab_].equals("首页"))) {
			// 判断压栈的poi个数，当栈中无元素时，表示还未显示一个可用页面，此时点击“首页�?按钮无效�?
			// 显示进度提示
			BaseView.mid_.waitDialog_.showProgressdialog((BaseView) this.getContext());
			invalidate();
			BaseView.mid_.poiRepo_.removeAllActionPoi();
			final BaseView bvFinal = bv;
			new Timer().schedule(new TimerTask() {

				@Override
				public void run() {
					BaseView.mid_.gotoMainView(bvFinal, false);
				}
			}, 600);
		} else {
			BaseView.mid_.removeDisplayable();
			if (BaseView.mid_.poiRepo_ != null)
				BaseView.mid_.poiRepo_.removeAllActionPoi();// clear stack.
			BaseView.mid_.pushDisplayable(Mid.MAIN_VIEW, null, Constant.MAIN_TITLE);
			BaseView.mid_.channelRepo_.setCurrentChannelID(StatusBar.ARRVALUE[currentTab_]);
			stepIntoView(StatusBar.ARRVALUE[currentTab_], null);
		}
	}

	protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
		if (gainFocus)
			focus_ = true;
		super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_DPAD_CENTER:
		case KeyEvent.KEYCODE_DPAD_LEFT:
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			keyGameAction(keyCode);
			break;
		case KeyEvent.KEYCODE_DPAD_DOWN:
			this.requestFocus();
			return super.onKeyDown(keyCode, event);
		default:
			return super.onKeyDown(keyCode, event);
		}
		return true;
	}

	boolean keyGameAction(int keyCode) {
		boolean isAction = false;
		switch (keyCode) {
		case KeyEvent.KEYCODE_DPAD_LEFT:
			if (currentTab_ > 0) {
				currentTab_--;
//				setTab(currentTab_, keyCode);
				setTab(currentTab_);
				this.invalidate();
				ViewGroup vg = (ViewGroup) this.getParent();
				if (vg instanceof StatusBar) {
					changeSelectTab();
				} else {
					changeTab();
				}
			}
			isAction = true;
			break;
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			boolean b = false;
			b = currentTab_ < size() - 1;
			if (b) {
				currentTab_++;
//				setTab(currentTab_, keyCode);
				setTab(currentTab_);
				this.invalidate();
				ViewGroup vg = (ViewGroup) this.getParent();
				if (vg instanceof StatusBar) {
					changeSelectTab();
				} else {
					changeTab();
				}
			}
			isAction = true;
			break;
		case KeyEvent.KEYCODE_DPAD_CENTER:
			if (focus_)
				isAction = true;
			break;
		default:
			break;
		}
		return isAction;
	}

	public void setTab(int currentTab) {
		int length = 0;
		int tabWidth = totalWidth_/tabSize_;
		x_ = 0;
		for (int i = 0; i < tabSize_; i++) {
			if (i == currentTab) {
				break;
			}
			length += tabWidth;
		}

		if ((length + tabWidth) > (-x_ - lengthBitmap_ + width_))
			// 校正标签右端
			x_ = width_ - length - tabWidth - (lengthBitmap_ << 1);
	}
	

	public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		setMeasuredDimension(width_, height_);
	}

	protected void onDraw(Canvas g) {
		// 设置字体非抗锯齿效果，使字体边�?�更平�?
		font_.setAntiAlias(true);
		if (this.arrText_ == null || this.arrText_.length < 1) {
			return;
		}
		int posX = 0;
		int posY = 0;
		// paint background.
		if (null != imgBackground_)
			g.drawBitmap(imgBackground_, 0, 0, font_);
		if (isImgUnit_) {
			posY += TAB_TEXT_ABOVE_MARGIN;
			// paint text tabs.
			posX = x_ + arrowWidth_;
			int tabWidth = 0;
			// Typeface font = Utils.setSONGTI(Typeface.BOLD);
			// font_.setTypeface(font);
			for (int i = 0; i < tabSize_; i++) {
				String text = this.arrText_[i];
				tabWidth = Math.max((int) (font_.measureText(text) + (TAB_TEXT_MARGIN_X << 1)), arrBitmap_[i].getWidth());
				// paint texts.
				if (i == currentTab_) {
					font_.setColor(Color.rgb(251, 117, 0));
					g.drawBitmap(this.arrBitmapD_[i], posX + ((tabWidth - arrBitmap_[i].getWidth()) >> 1), 0, font_);
				} else {
//					font_.setColor(Color.LTGRAY);
					font_.setColor(Color.BLACK);
					g.drawBitmap(this.arrBitmap_[i], posX + ((tabWidth - arrBitmap_[i].getWidth()) >> 1), 0, font_);
				}
				// 控件中显示的字符�?
				g.drawText(text, posX + ((tabWidth - (int) font_.measureText(text)) >> 1), this.arrBitmap_[i].getHeight() - 3, font_);
				posX += tabWidth;
			}

		} else {
			// 箭头图片的宽高�?暂定为宽高一�?为矩�?
			posY += TAB_TEXT_ABOVE_MARGIN;
			// paint text tabs.
			posX = x_ + arrowWidth_;
			int tabWidth = 0;
//			int currentx = 0;
//			int currentlen = 0;
			// 圆角矩形的弧度
			int radian = 10;
			// Typeface font = Utils.setSONGTI(Typeface.BOLD);
			// font_.setTypeface(font);
			for (int i = 0; i < tabSize_; i++) {
				String text = this.arrText_[i];
				tabWidth = (int) (font_.measureText(text) + (TAB_TEXT_MARGIN_X << 1));
				font_.setColor(bgColor_);
//				int leftBackground = posX + 1;
//				int rightBackground = leftBackground + tabWidth - 2;
				// paint texts.
				if (i == currentTab_) {
					if (this.isFocused()) {
//						int topHightLight = posY + 2;
//						int bottomEdge = topHightLight + height_ - 2;
						font_.setColor(BaseView.HL_TABBAR_COLOR);
						font_.setStyle(Style.FILL);
						g.drawRoundRect(new RectF(posX + 2, ((int) (height_ - font_.getTextSize()) >> 1) - 3, posX + tabWidth - 2, ((int) (height_ + font_.getTextSize()) >> 1) + 2), radian, radian, font_);
					}
					font_.setColor(focusTextColor_);
				} else {
					font_.setColor(textColor_);
				}
				// 控件中显示的字符
				g.drawText(text, posX + ((tabWidth - (int) font_.measureText(text)) >> 1), ((height_ + (int) font_.getTextSize()) >> 1) - 2, font_);
				posX += tabWidth;
			}
		}
		boolean isOn = false;
		if (currentTab_ != 0) {
			isOn = true;
		}
		// 左箭头图片
		Bitmap arrowIconLeft = isOn ? arrowIconLeftOn_ : arrowIconLeftOff_;
		// 画左箭头的Y位置
		g.drawBitmap(arrowIconLeft, 0, 0, font_);
		// paint right arrow.
		isOn = false;
		if (currentTab_ != size() - 1) {
			isOn = true;
		}
		// 右箭头图片
		Bitmap arrowIconRight = isOn ? arrowIconRightOn_ : arrowIconRightOff_;
		g.drawBitmap(arrowIconRight, width_ - arrowWidth_, 0, font_);
	}

	public void changeTab() {
		BaseView bv = (BaseView) this.getContext();
		bv.tabBar_.clickArrows(bv);
		if (null != listener_) {
			listener_.componentAction(this, bv);
		} else {
			bv.listener_.componentAction(this, bv);
		}
		bv.tabBar_.getContentLayout().invalidate();
	}

	private int size() {
		return this.arrText_.length;
	}

	void setComponentLister(ComponentListener listener) {
		listener_ = listener;
	}

	void reset() {
		arrText_ = null;
		// this.llH_.removeAllViews();
		totalTabW_ = 0;
		currentTab_ = 0;
		saveCurrentTab_ = currentTab_;
	}

	public void setCurrentTab(int currentTab) {
		currentTab_ = currentTab;
	}

	/**
	 * Enter the view below main view. It's maybe a detail view with a tab, or an account list view without a tab.
	 */
	private void stepIntoView(String mainChannelID, String subChannelID) {
		Channel mainChannel = BaseView.mid_.channelRepo_.getChannel(mainChannelID);
		BaseView.mid_.channelEntity_.gotoDetailViewFromMainView(subChannelID, (BaseView) this.getContext(), Mid.DETAIL_VIEW, mainChannel.id(), mainChannel.title());
	}

	// 横竖屏转换时调用该方法改变tab的相关尺寸和布局定位
	public static void changeTabSize(TabItem tab, Bitmap bitmap) {
		tab.width_ = Utils.screenWidth_;
		// 重新构�?背景图�?
		TabItem.imgBackground_ = null;
		TabItem.imgBackground_ = Utils.makeButton(bitmap, Utils.screenWidth_);
		if (tab.totalWidth_ <= Utils.screenWidth_) {
			// 如果tab的�?长小于或者等于翻转后的屏幕宽，则只是把定位X设置�?
			tab.x_ = 0;
		} else {
			// 如果tab的�?长大于翻转后的屏幕宽，则先看被�?中单元出于为翻转前的�?��位�?
			int sumLength = 0;
			int singleLength;
			if (TabItem.currentTab_ == 0) {
				// 如果被�?中为第一个单元，则不变�?
			} else {
				for (int i = 0; i < TabItem.currentTab_; i++) {
					singleLength = (int) (tab.font_.measureText(tab.arrText_[i]) + (tab.TAB_TEXT_MARGIN_X << 1));
					sumLength = sumLength + singleLength;
				}
				int remain = sumLength - (-tab.x_ - tab.arrowWidth_);

				// 该处算的是翻转之前的界面百分比（翻转后宽高对换）
				float percent = (float) ((remain * 1.0) / Utils.screenHeight_);
				// 翻转后被选中位置离屏幕最左方的距离（保持与翻??�前的比例一样）
				int lengthTemp = (int) (Utils.screenWidth_ * percent);
				tab.x_ = -(sumLength - lengthTemp);
				if (tab.x_ >= 0)
					tab.x_ = 0;
				int limitX = Math.min(Utils.screenWidth_, Utils.screenHeight_) - tab.totalWidth_ - (tab.lengthBitmap_ << 1);
				if ((tab.x_ < limitX) && (limitX < 0))
					tab.x_ = limitX;
			}
		}
		tab.invalidate();
		// 该处�?��要重新设置一下管理器??�宽???
		ViewGroup vg = (ViewGroup) tab.getParent();
		if (vg instanceof LinearLayout) {
			LinearLayout ll = (LinearLayout) vg;
			ll.setLayoutParams(new LayoutParams(Utils.screenWidth_, LayoutParams.WRAP_CONTENT));
		}
	}

	public void cleanText() {
		// TODO Auto-generated method stub

	}

	public String getContentText() {
		// TODO Auto-generated method stub
		return null;
	}

	public CssStyle getCssStyle() {
		// TODO Auto-generated method stub
		return null;
	}

	public int getCmpHeight() {
		// TODO Auto-generated method stub
		return 0;
	}

	public View getCmpView() {
		// TODO Auto-generated method stub
		return null;
	}

	public int getCmpWidth() {
		// TODO Auto-generated method stub
		return 0;
	}

	public boolean isInTable() {
		// TODO Auto-generated method stub
		return false;
	}

	public void mould() {
		// TODO Auto-generated method stub

	}

	public void releaseResource(View view) {
		// TODO Auto-generated method stub
		label_ = null;
		font_ = null;
		arrText_ = null;
		if (null != imgBackground_ && !imgBackground_.isRecycled()) {
			imgBackground_.recycle();
		}
		imgBackground_ = null;

		arrBitmap_ = null;
		arrBitmapD_ = null;
		if (null != arrowIconLeftOn_ && !arrowIconLeftOn_.isRecycled()) {
			arrowIconLeftOn_.recycle();
		}
		arrowIconLeftOn_ = null;

		if (null != arrowIconLeftOff_ && !arrowIconLeftOff_.isRecycled()) {
			arrowIconLeftOff_.recycle();
		}
		arrowIconLeftOff_ = null;

		if (null != arrowIconRightOn_ && !arrowIconRightOn_.isRecycled()) {
			arrowIconRightOn_.recycle();
		}
		arrowIconRightOn_ = null;

		if (null != arrowIconRightOff_ && !arrowIconRightOff_.isRecycled()) {
			arrowIconRightOff_.recycle();
		}
		arrowIconRightOff_ = null;
	}

	public void setContentText(String text) {
		// TODO Auto-generated method stub

	}

	public void setCssStyle(CssStyle style) {
		// TODO Auto-generated method stub

	}

	public void setInTable(boolean inTable) {
		// TODO Auto-generated method stub

	}

	public void setCmpHeidht(int height) {
		// TODO Auto-generated method stub

	}

	public void setCmpWidth(int width) {
		// TODO Auto-generated method stub

	}

	public void shrinkWidth() {
		// TODO Auto-generated method stub

	}

	public void setForm(FormLayout formLayout) {
		// TODO Auto-generated method stub

	}

	public FormLayout getForm() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setEncrypt(String encrypt) {
		// TODO Auto-generated method stub

	}
}
